package com.github.tommas.admintpl.security.permission;

import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.permission.PermissionResolver;

import java.util.Arrays;
import java.util.HashSet;

public class RestrictedPermissionResolver implements PermissionResolver {
    public static final String ATTRIBUTE_START_TOKEN = "[";
    public static final String ATTRIBUTE_END_TOKEN = "]";
    public static final String ATTRIBUTE_DIVIDER = ",";
    @Override

    public Permission resolvePermission(String permissionString) {
        int attrStartPos = permissionString.indexOf(ATTRIBUTE_START_TOKEN);
        if (attrStartPos < 0) {
            return new RestrictedPermission(permissionString);
        }

        int attrEndPos = permissionString.indexOf(ATTRIBUTE_END_TOKEN, attrStartPos);
        if (attrEndPos < 0) {
            throw new RuntimeException(String.format("Invalid permission string: %s", permissionString));
        }

        String attrs = permissionString.substring(attrStartPos+1, attrEndPos);
        return new RestrictedPermission(permissionString.substring(0, attrStartPos),
                new HashSet<>(Arrays.asList(attrs.split(ATTRIBUTE_DIVIDER))));
    }
}
